package com.cl.code.database.mybatis.module.sql;

import com.cl.code.database.mybatis.module.sql.table.TableField;
import com.cl.code.database.mybatis.module.sql.table.TableInfo;
import com.cl.code.database.mybatis.module.sql.table.TableInfoFactory;
import lombok.Getter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chengliang
 * @since 1.0.0
 */
@Getter
public class View<Entity> {

    private final Class<Entity> entityClass;

    private final Map<String, String> map = new HashMap<>(10);

    private View(Class<Entity> entityClass) {
        this.entityClass = entityClass;
    }

    public static <Entity> View<Entity> of(Class<Entity> tClass) {
        return new View<>(tClass);
    }

    public View<Entity> column(Fn<Entity, Object> column) {
        map.put(column.getName(), column.getName());
        return this;
    }

    public String getViewSql() {
        if (map.isEmpty()) {
            return "";
        }
        TableInfo tableInfo = TableInfoFactory.getTableInfo(getEntityClass());
        TableField[] fieldItems = tableInfo.getTableFields();
        String[] filedArray = Arrays.stream(fieldItems)
                .filter(item -> map.containsKey(item.getFieldName())).map(TableField::getSqlFieldName).toArray(String[]::new);
        return String.join(",", filedArray);
    }


}
